import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.apache.log4j.Logger;

public class NettyTesthandle extends ChannelInboundHandlerAdapter {

	Logger logger = Logger.getLogger("server");

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		System.out.println(ctx.channel() + "连接上");

	

		
		// byteBuf.writeShort(0X8884);
		// byteBuf.writeShort(0XAA33);
		// byteBuf.writeShort(0X2234);
		// byteBuf.writeShort(0XAA55);

		// byteBuf.writeShort(0x018b);
		// byteBuf.writeShort(0x3e81);
		// byteBuf.writeShort(0x0001);
		// byteBuf.writeShort(0x000A);
		// byteBuf.writeByte(0x01);
		// byteBuf.writeShort(0xaa55);
		/**
		 * 
		 * 55aa0100 018b 3e81 0035 000a 0000000000 00000001 000000 00
		 * 0004002e007000000000700760
		 * ab0070000000007000000050e4e1c070989680700000007000000072faf080000000000000048ec5
		 * aa55
		 */
		ByteBuf byteBuf = ctx.alloc().buffer();
		byteBuf.writeInt(0X55AA0100);
		byteBuf.writeShort(0x018b);
		byteBuf.writeShort(0x3e81);
		byteBuf.writeShort(0x0035);
		byteBuf.writeShort(0x000a);
		byteBuf.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 });
		byteBuf.writeInt(0x00000001);
		byteBuf.writeBytes(new byte[] { 0x00, 0x00, 0x00 });
		byteBuf.writeByte(0x00);

		byteBuf.writeBytes(new byte[] { 
				0x00, 0x04, 0x00, 0x2e, 0x00, 0x70,
				0x00, 0x00, 0x00, 0x00, 0x70, 0x07, 0x60, 0x0b, 0x00, 0x70,
				0x00, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00, 0x50, 0x04,
				0x01, 0x00, 0x70, 0x08, 0x06, 0x00, 0x70, 0x00, 0x00, 0x00,
				0x70, 0x00, 0x00, 0x00, 0x72, 0x0a, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x00, 0x00, 0x00, 0x04, 0x0e, 0x05

		});
		byteBuf.writeInt(0xaa55);
		ctx.writeAndFlush(byteBuf);
		super.channelActive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {

		// ByteBuf buf=(ByteBuf)msg;
		//
		// CharSequence charSequence=
		// buf.getCharSequence(buf.readerIndex(), buf.readableBytes(),
		// Charset.forName("utf-8"));
		//
		// System.out.println(charSequence);
		// super.channelRead(ctx, msg);

		ByteBuf buf = (ByteBuf) msg;
		StringBuilder builder = new StringBuilder();
		while (buf.readableBytes() > 0) {

			String str = Integer.toHexString(buf.readUnsignedByte());

			if (str.length() == 1)
				str = "0" + str;
			builder.append(str);
		}
		logger.debug("读取数据转化成字符串后：" + builder.toString());
	}

}
